package com.ht.searchrooky.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.inject.Inject;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.stereotype.Repository;

import com.ht.searchrooky.dao.UserDao;
import com.ht.searchrooky.domain.User;

@Repository
public class UserDaoJDBCImpl implements UserDao {

	private static final String SQL_INSERT_USER = "insert into t_user (user_name,password,mail,enable,role) values (?,?,?,?,?)";

	private static final String SQL_UPDATE_USER = "update t_user set age = ?"
			+ "where id = ?";

	private static final String SQL_SELECT_USER = ""
			+ "select id, user_name,password, mail,role from t_user";

	private static final String SQL_SELECT_USER_BY_ID = SQL_SELECT_USER
			+ " where id=?";

	private static final String SQL_SELECT_USER_BY_NAME = SQL_SELECT_USER
			+ " where user_name=?";

	@Inject
	private JdbcTemplate jdbcTemplate;

	@Override
	public User getUserByName(final String userName) {
		final User user = new User();
		UserCallbackHandler userCallbackHandler = new UserCallbackHandler(user);
		jdbcTemplate.query(SQL_SELECT_USER_BY_NAME, new Object[] { userName },
				userCallbackHandler);
		return user;
	}

	

	@Override
	public User getUserById(int uid) {
		final User user = new User();
		UserCallbackHandler userCallbackHandler = new UserCallbackHandler(user);
		jdbcTemplate.query(SQL_SELECT_USER_BY_ID, new Object[] { uid },
				userCallbackHandler);
		return user;
	}

	@Override
	public void deletUser(User user) {

	}

	@Override
	public List<User> getUserList() {
		return getJdbcTemplate().query(SQL_SELECT_USER,
				new ParameterizedRowMapper<User>() {

					@Override
					public User mapRow(ResultSet rs, int rowNum)
							throws SQLException {
						User user = new User();
						user.setId(rs.getInt(1));
						System.out.println(user);
						return user;
					}
				});
	}

	@Override
	public User updateUser(User user) {
		return null;
	}
	
	static class UserCallbackHandler implements RowCallbackHandler {
		private User user;

		public UserCallbackHandler(User user) {
			super();
			this.user = user;
		}

		@Override
		public void processRow(ResultSet rs) throws SQLException {
			user.setId(rs.getInt("id"));
			user.setPassword(rs.getString("password"));
			user.setUser_name(rs.getString("user_name"));
			user.setMail(rs.getString("mail"));
			user.setRole(rs.getString("role"));
		}
	}
	
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}
